package util;

import gui.panel.WorkingPanel;

import javax.swing.*;
import java.awt.*;

public class CenterPanel extends JPanel {
    private double rate;
    private JComponent c;
    private boolean strech;

    public CenterPanel(double rate,boolean strech)
    {
        this.setLayout(null);
        this.rate = rate;
        this.strech = strech;
    }

    public CenterPanel(double rate)
    {
        this(rate,true);
    }

//    public void repaint()
//    {
//        //缩放显示
////        if(c != null)
////        {
////            Dimension containerSize = this.getSize();//JPanel's Size
////            Dimension componentSize = c.getSize();//JComponent's Size
////
////            if(strech)
////                c.setSize((int)(containerSize.width * rate), (int)(containerSize.height * rate));
////            else
////                c.setSize(componentSize);
////
////            c.setLocation((containerSize.width - c.getSize().width) / 2, (containerSize.height - c.getSize().height) / 2);
////
////        }
//
//        super.repaint();
//
//    }

    public void show(JComponent jComponent)
    {
        this.c = jComponent;
        Component[] cs = this.getComponents();
        for(Component c:cs)//删除当前mainpanel的workpanel内的所有组件
        {
            remove(c);
        }
        add(jComponent);

        if(jComponent instanceof WorkingPanel)
            ((WorkingPanel)jComponent).updateData();

        zoom();
        this.updateUI();//调用repaint,否则切换panel时不显示
    }

    private void zoom() {
        //缩放显示，设置传入的组件大小
        if(c != null)
        {
            Dimension containerSize = this.getSize();//JPanel's Size
            Dimension componentSize = c.getSize();//JComponent's Size

            if(strech)
                c.setSize((int)(containerSize.width * rate), (int)(containerSize.height * rate));
            else
                c.setSize(componentSize);

            c.setLocation((containerSize.width - c.getSize().width) / 2, (containerSize.height - c.getSize().height) / 2);

        }
    }
}
